// 2024 - Modified by MetaX Integrated Circuits (Shanghai) Co., Ltd. All Rights
// Reserved.
/**
 *
 *   @file utils.hpp
 *
 *   @brief utils funtions
 *
 *   cuThomasBatch is a software package provided by
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion
 *
 *   @author Ivan Martinez-Perez ivan.martinez@bsc.es
 *   @author Pedro Valero-Lara   pedro.valero@bsc.es
 *
 **/

#include <sys/time.h>
#include <time.h>
#include <cmath>

/**
 *  Return time in seconds since arbitrary time in the past.
 *  Used for elapsed wall clock time computation.
 **/
double time_wtime(void) {
  struct timeval t;
  gettimeofday(&t, NULL);
  return t.tv_sec + t.tv_usec * 1e-6;
}

/**
 * Version callable from Fortran stores seconds in the parameter time.
 **/
void timef_wtime(double *time) { *time = time_wtime(); }

template <typename T> void calcError(T *src, T *dst, int size) {
  double sumSquaredError = 0;
  for (int i = 0; i < size; ++i) {
    double error = src[i] - dst[i];
    sumSquaredError += error * error;
  }
  auto rmse = std::sqrt(sumSquaredError / size);
  printf("RMSE: %.8f\n", rmse);
  if (rmse > 1e-8)
    printf("FAIL\n");
  else
    printf("PASS\n");
}

template <typename T> void calcError_print(T *src, T *dst, int size) {

  double error = 0;

  for (int i = 0; i < size; ++i) {
    printf("src: %e - dst: %e\n", src[i], dst[i]);

    if (error < std::fabs(std::fabs(src[i]) - std::fabs(dst[i]))) {
      error = std::fabs(std::fabs(src[i]) - std::fabs(dst[i]));
    }
  }
  printf("Maximum error: %e\n", error);
}
